package com.bizmda.bizsip.app.client;

import lombok.Getter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shizhengye
 */
@Getter
public class DelayAppServiceClientProxy<T> implements InvocationHandler {

    private final Class<T> mapperInterface;
    private final Map<Method, DelayAppServiceClientMethod> methodCache;
    private final String bizServiceId;
    private final int[] delayMilliseconds;

    public DelayAppServiceClientProxy(Class<T> mapperInterface, String bizServiceId, int[] delayMilliseconds) {
        this.mapperInterface = mapperInterface;
        this.methodCache = new HashMap<>();
        this.bizServiceId = bizServiceId;
        this.delayMilliseconds = delayMilliseconds;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        final DelayAppServiceClientMethod delayAppServiceClientMethod = cachedMapperMethod(method);

        return delayAppServiceClientMethod.execute(args);
    }

    private DelayAppServiceClientMethod cachedMapperMethod(Method method) {
        return methodCache.computeIfAbsent(method,
                key -> new DelayAppServiceClientMethod(key, this));
    }

}
